package give.replay;

import give.replay.GameEvent;
import give.comm.ActionMessage;
import give.comm.Message;
import give.world.World;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: koller
 * Date: Oct 18, 2009
 * Time: 8:51:48 PM
 * To change this template use File | Settings | File Templates.
 */
public class DatabaseGameLogSource {
//    private Connection connection;
    private PreparedStatement gameInfoStmt, gameLogStmt;

    public DatabaseGameLogSource(Connection connection) throws SQLException {
//        this.connection = connection;

        gameInfoStmt = connection.prepareStatement("select * from games where id=?");
        gameLogStmt = connection.prepareStatement("select * from game_logs where gameid=? order by id");
    }

    public String getWorldName(int gameId) throws SQLException {
        gameInfoStmt.setInt(1, gameId);

        ResultSet rs = gameInfoStmt.executeQuery();

        while( rs.next() ) {
            return rs.getString("world_name");
        }

        return null;
    }

    public List<GameEvent> getEvents(int gameId, World world) throws SQLException {
        List<GameEvent> ret = new ArrayList<GameEvent>();

        gameLogStmt.setInt(1, gameId);
        ResultSet rs = gameLogStmt.executeQuery();

        while( rs.next() ) {
            String msgString = rs.getString("message");
            Message msg = Message.parse(msgString);

            if( msg == null ) {
                System.err.println("ignoring message: " + msgString);
            } else {
                if( msg instanceof ActionMessage ) {
                    ((ActionMessage) msg).findAction(world);
                }
                
                ret.add(new GameEvent(new Date(rs.getLong("timestamp_ms")), msg));
            }
        }

        rs.close();

        return ret;
    }
}
